<?php

namespace Tbf\Bundle\TaskManageBundle;

use Psr\Log\LoggerInterface;
use Symfony\Component\DependencyInjection\ContainerAware;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Tbf\Bundle\QueueBundle\QueueManager;

class JobTriggerListener implements EventSubscriberInterface
{
    protected $queue_manager;
    protected $logger;
    public function __construct(QueueManager $queue_manager,
                         ContainerInterface $container,
                         LoggerInterface $logger){
        $this->queue_manager = $queue_manager;
        $this->container = $container;
        $this->logger = $logger;
    }
    public static function getSubscribedEvents()
    {
        return array('job_trigger'=>'onTrigger');
    }
    public function onTrigger()
    {
        //执行10个任务
        for($i=0;$i<10;$i++){
            list($task,$err) = $this->queue_manager->getQueue('tbf_task_manager')->read();
            if ($err==='EOF') {
                return;
            }
            if ($err!==null) {
                throw new TaskManagerException($err);
            }
            if ($task instanceof ContainerAware) {
                $task->setContainer($this->container);
            }
            $this->logger->debug('task manager run a task',array(
                'class_name'=>get_class($task)
            ));
            $task->run();
        }
    }
}
